<?php
/**
 * 后台管理加载器
 * @category     Shuxun Cms
 * @date         2015年9月21日
 * @author       Shuxun Team <kaiping.jiang@scshux.com>
 * @file         Module.php
 */
namespace Scshux\Front;

use Phalcon\Loader, Phalcon\Mvc\Dispatcher, Phalcon\Mvc\View, Phalcon\Mvc\ModuleDefinitionInterface;
use Phalcon\Di\FactoryDefault;

class Module implements ModuleDefinitionInterface {

	/**
	 * Register a specific autoloader for the module
	 */
	public function registerAutoloaders(\Phalcon\DiInterface $dependencyInjector = null){

		$loader = new Loader ();
		$loader->registerNamespaces ( array (
				'Scshux\Front\Controllers' => APPLICATION_PATH . '/modules/front/controllers/'
		) );
		$loader->register();

	}

	/**
	 * Register specific services for the module
	 */
	public function registerServices(\Phalcon\DiInterface $di) {

		$config = FactoryDefault::getDefault()->get('config');
		$config->currentModule='front';

		$coreObj = $di->get('core');
		/* @var $coreObj \Scshux\Plugin\Core */

		//view
		$view = $di->get('view');
		if($coreObj->getSiteID() == 2){
			$view->setViewsDir (APPLICATION_PATH . '/design/front/en/template/');
		}else{
			$view->setViewsDir (APPLICATION_PATH . '/design/front/cn/template/');
		}


		//event
		$eventsManager = $di->getShared('eventsManager');
		$eventsManager->attach("dispatch:beforeDispatchLoop", function ($event, $dispatcher) use ($di,$view) {
			new \Scshux\Plugin\Acl($dispatcher,$view);
		});


		// Registering a dispatcher
		$di->set ( 'dispatcher', function () use ($di,$eventsManager){
			$dispatcher = new Dispatcher ();
			$dispatcher->setDefaultNamespace ( "Scshux\Front\Controllers" );
			$eventsManager->attach(
					"dispatch:beforeException",
					function($event, $dispatcher, $exception)
					{
						switch ($exception->getCode()) {
							case Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
							case Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
								$dispatcher->forward(
									array("namespace" => "Scshux\Front\Controllers",'controller' => 'errors', 'action' => 'err404')
								);
							return false;
						}
					}
			);
			$dispatcher->setEventsManager($eventsManager);
			return $dispatcher;
		});

	}
}